﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;

namespace Chapter5Lesson1OrderProcessor
{
    class Program
    {
        static void Main(string[] args)
        {
            const string fileName = "Orders.xml";

            //ParseWithXmlDocument(fileName);
			ParseWithXDocument(fileName);
            Console.ReadLine();
        }

        static void ParseWithXmlDocument(String filePath)
        {
            var sw = new Stopwatch();
            sw.Start();
            double totalOrderPrice = 0;
            double totalFreight = 0;
            Int32 orderCount = 0;

            var doc = new XmlDocument();
            doc.Load(filePath);
            orderCount = doc.SelectNodes("//Order").Count;

            var lineItems = doc.SelectNodes("//LineItem");

            foreach (XmlNode lineItem in lineItems)
            {
                var nodeFreight = double.Parse(lineItem.Attributes["Freight"].Value);
                var nodePrice = double.Parse(lineItem.Attributes["Price"].Value) * double.Parse(lineItem.Attributes["Qty"].Value);

                totalOrderPrice += nodeFreight + nodePrice;
                totalFreight += nodeFreight;
            }

            Console.WriteLine("Total order price - {0}", totalOrderPrice);
            Console.WriteLine("Total freight price - {0}", totalFreight);
            Console.WriteLine("Average cost of freight - {0}", totalFreight / orderCount);

            sw.Stop();
            Console.WriteLine("Time elapsed for parsing xml doc - {0}", sw.Elapsed);
        }

		static void ParseWithXDocument(String filePath)
		{
			var sw = new Stopwatch();
			sw.Start();

			decimal totalOrdersPrice = 0;
			decimal totalFreight = 0;
			int totalOrderQty = 0;

			var doc = XDocument.Load(filePath);

			var orders = doc.Descendants("Order");

			foreach (var order in orders)
			{
				totalOrderQty++;

				var lineItems = order.Descendants("LineItem");
				foreach (var lineItem in lineItems)
				{
					var freight = (Decimal) lineItem.Attribute("Freight");
					var orderPrice = (Decimal) lineItem.Attribute("Price");
					var localQty = (Int32) lineItem.Attribute("Qty");

					totalFreight += freight;
					totalOrdersPrice += orderPrice * localQty + freight;
				} 
			}

			Console.WriteLine("Total freight - {0:C}", totalFreight);
			Console.WriteLine("Total orders price - {0:C}", totalOrdersPrice);
			Console.WriteLine("Average freight cost per order - {0:C}", totalFreight / totalOrderQty);

			sw.Stop();
			
			Console.WriteLine("Time elapsed with using xdocument - {0}", sw.Elapsed);
		}
    }
}
